/* 
 * Copyright [2018] [Alex/libo(liboms@hotmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.jpdf.utility;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import com.hyts.jpdf.config.PdfConfig;

import freemarker.template.Configuration;
import freemarker.template.Template;

/** 
 * @title FreemarkerUtil.java  
 * @package com.hyts.jpdf.utility  
 * @description TODO  
 * @see TODO
 * @author libo/Alex
 * @email liboms@hotmail.com/liboware@163.com  
 * @date 2018年5月24日 
 * @version V1.0 
 */
public final class FreemarkerUtil {

	
     private static Configuration freemarkerCfg = null;
	
	 static {
	        freemarkerCfg = new Configuration();
	        //freemarker的模板目录
	        try {
	            freemarkerCfg.setDirectoryForTemplateLoading(new File(PathUtil.getCurrentPath()));
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	 }
	 
	 /**
	     * freemarker渲染html
	     */
	    public static String freeMarkerRender(Map<String, Object> data, String htmlTmp) {
	        Writer out = new StringWriter();
	        try {
	            // 获取模板,并设置编码方式
	            Template template = freemarkerCfg.getTemplate(htmlTmp);
	            template.setEncoding(PdfConfig.DEFAULT_PDF_HTML_CHARSET);
	            // 合并数据模型与模板
	            template.process(data, out); //将合并后的数据和模板写入到流中，这里使用的字符流
	            out.flush();
	            return out.toString();
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                out.close();
	            } catch (IOException ex) {
	                ex.printStackTrace();
	            }
	        }
	        return null;
	    }

	
	
}
